﻿using System;
using System.Windows.Forms;
using Autofac;
using LocalOverride.Fiddler;
using LocalOverride.Fiddler.UI;
using LocalOverride.Fiddler.UrlMapping;
using LocalOverride.Proxy;

namespace LocalOverride
{
    public partial class LocalOverrideMain : Form
    {
        private readonly IContainer container;
        private readonly MappingRegistryFactory mappingRegistryFactory;
        private readonly ILogger logger;

        public LocalOverrideMain()
        {
            container = ComponentBuilder.SetupAutoFac();
            mappingRegistryFactory = container.Resolve<MappingRegistryFactory>();

            InitializeComponent();

            var proxy = new HttpProxy(8889);

            logger = container.Resolve<ILogger>();

            proxy.Start(
                (requestUrl) =>
                {
                    
                    var overrideMapping = mappingRegistryFactory.Create();
                    var requestUri = new Uri(requestUrl);
                    var mapping = overrideMapping.GetMapping(requestUri);

                    if (mapping != MappingResult.NoMapping)
                    {
                        logger.Log(String.Format("Mapping: {0} to {1}", requestUri, mapping.LocalFile));

                        return new InterceptResult { ResultType = InterceptResultType.File, FileName = mapping.LocalFile };
                    }

                    return new InterceptResult { ResultType = InterceptResultType.File, FileName = @"c:\\temp\\test.html" };
                }

    );
        }

        private TabPage oPage;
        private Control oEditor;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            oPage = new TabPage("Local Override");

            var presenter = container.Resolve<MappingEditorPresenter>();
            oEditor = (Control)presenter.View;

            container.Resolve<LoggingPresenter>();

            oPage.Controls.Add(oEditor);

            oEditor.Dock = DockStyle.Fill;
            tabContainer.TabPages.Add(oPage);
        }

        private void LocalOverrideMain_Load(object sender, EventArgs e)
        {

        }
    }
}
